import React, { Component } from 'react';
import { Flex, Button, Toast } from "antd-mobile"
import { Login } from "dcloud-mobile"
import Router from "umi/router";
import Link from 'umi/link'
import { connect } from "dva/index";
import style from './index.less';
import { httpUtil, loginServer } from 'dcloud-utils';
import { httpUrl, commonReq } from 'dcloud-core';


// const {Item} = List

export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loginItem: [
                {
                    title: '手机号',
                    type: 'number',
                    key: 'mobile',
                    extra: '',
                    editable: true,
                    disabled: false,
                    defaultValue: '',
                    maxLength: 13,
                    validatorCallBack: this.testPhone.bind(this),
                    onBlurCallBack: this.onBlurTest.bind(this),
                    onFocusCallBack: this.onFocusTest.bind(this)
                },
                {
                    type: 'text',
                    key: 'code',
                    extra: this.code(),
                    editable: true,
                    disabled: false,
                    maxLength: 8,
                    validatorCallBack: this.testImagCode.bind(this),
                    placeholder: '请输入图形验证码',
                    onBlurCallBack: this.onBlurTest.bind(this),
                    onFocusCallBack: this.onFocusTest.bind(this),
                }
            ],
            ad: JSON.parse(localStorage.getItem("ad"))
        }
        // console.log( global.ad );
    }

    // 图形验证码
    testImagCode(rule, value, callback) {
        commonReq.imagCode(value, '').then((_value) => {
            callback();
        }).catch((e) => {
            callback(e);
        });
    }

    // 手机号正则
    testPhone(rule, value, callback) {
        commonReq.mobile(value, '').then((_value) => {
            callback();
        }).catch((e) => {
            callback(e);
        });
    }

    // 获取手机验证码
    getCode(form) {
        form.validateFields({ force: true }, (error) => {
            const params = Object.assign({}, form.getFieldsValue());
            httpUtil.get(httpUrl.hvcode, { mobile: params.mobile.replace(/\s+/g, ""), captcha: params.code, rst: localStorage.getItem('rst'), t: new Date().getTime() }).then((response) => {
                if (response.code == 200) {
                    Toast.info("发送成功", 1)
                } else {
                    Toast.fail(response.msg, 2);
                }
            }).catch(error => {
                Toast.fail('系统错误', 2);
            })
        });
    }



    changeCode() {
        console.log('更换图片验证码')
        // 请求数据
        let data = [...this.state.loginItem];
        data[1].extra = this.code()
        this.setState({
            loginItem: data
        })
    }

    // 验证码图片
    code() {
        return (
            <img onClick={this.changeCode.bind(this)} className={'code'} src={httpUrl.getCode + '?t=' + new Date().getTime() + '&rst=' + localStorage.getItem('rst')} />
        )
    }

    // onBlurTest测试
    onBlurTest = (value) => {
        console.log('Blur', value)
        /*        this.props.dispatch({type:"base/addSelected",payload:'cart'});
                Router.push('/main/cart')*/
    }

    // onFocusTest测试
    onFocusTest = (value) => {
        console.log('Focus', value)
    }

    // 账号密码登录
    onSubmit(params) {
        console.log(params)
        httpUtil.post(httpUrl.mLogin, { mobile: params.mobile.replace(/\s+/g, ""), validCode: params.phoneCode, rst: localStorage.getItem('rst'), t: new Date().getTime()}, 'form').then((response) => {
            if (response.code == 200) {
                const ticket = response.data.ticket;
                // 验ticket
                const params = { appKey: httpUrl.appConfig.appKey, server: window.location.host, ticket: ticket, t: new Date().getTime() };
                httpUtil.get(httpUrl.ticket, params).then((response) => {
                  // 通过ticket 换到token 会在拦截器中处理201响应:src/core/httpUtilConfig/index.js
                  console.log('验证ticket后',response)
                }).catch(error => {
                    Toast.fail('系统错误', error);
                })
            }
        }).catch(error => {
            Toast.fail('系统错误', 2);
        })
        // 请求接口,返回token和用户数据
        // sessionStorage.setItem('token', '111');
        // sessionStorage.setItem('userInfo', '222');
        // loginServer.login();
    }

    //微信授权
    wxAuth() {
        loginServer.auth()
    }

    render() {
        return (
            <div>
                <Flex justify="between">
                    <Flex.Item>
                        <div className={style.center_top_bg}>
                            <div className={style.imgblock}>
                            </div>
                        </div>
                        <div className={style.loginInput} style={{ textAlign: 'center', width: '100%' }}>
                            <Login callWx={this.wxAuth.bind(this)} itemType={'login'} getCode={this.getCode.bind(this)} callSubmit={this.onSubmit.bind(this)} isWx={true} loginItem={this.state.loginItem} />
                            {this.state.ad? 
                            <div style={{marginTop:'1rem'}}>
                            <img onError={(e) => {e.target.onerror = null;e.target.src=""}} style={{margin:'0 auto', display: 'block', width: '100%', minHeight:'10px'}} src={this.state.ad.adUrl}></img> 
                            <p style={{margin:'0 auto', display: 'block', width: '100%'}} className={style.p}>{this.state.ad.advertisement}</p></div>
                            : null}
                        </div>
                    </Flex.Item>
                </Flex>
            </div>
        )
    }
}
